# !/usr/bin/env python
# -*- coding:utf-8 -*-
import io
import json
import logging
import requests

from conf import config
from helper.mp_helper import fetch_access_token
from util.json_util import JSONEncoder
from wechatpy import WeChatClient

logger = logging.getLogger("wechat.common")

APPID = config.MP_APP_ID
APPSECRECT = config.MP_APP_SECRET


class STMessage(object):
    @classmethod
    def SendTemplateMessage(cls, touser, template_id, link_url, data, topcolor="#7B68EE"):
        dict_data = {
            "touser": touser,
            "template_id": template_id,
            "topcolor": topcolor,
            "url": link_url,
            "data": data  # data为模板消息内容
        }
        access_token = fetch_access_token(APPID, APPSECRECT).get("access_token", "")

        if not access_token:
            logger.error("access_token获取失败")
            access_token = fetch_access_token(APPID, APPSECRECT, reset=True).get("access_token", "")

        json_data = json.dumps(dict_data, cls=JSONEncoder)
        base_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={token}"
        url = base_url.format(token=access_token)
        logger.info("url=%s" % url)
        counter = 0
        flag = True
        result = None

        while counter < 6 and flag:
            if counter == 3:
                access_token = fetch_access_token(APPID, APPSECRECT, reset=True).get("access_token", "")
                url = base_url.format(token=access_token)

            try:
                resp = requests.post(url=url, data=json_data, timeout=30)
            except Exception as e:
                logger.error("发送模版消息失败: %s" % e)
                counter += 1
                continue

            resp_data = resp.json()
            logger.info("resp_data=%s" % resp_data)

            if int(resp_data.get("errcode", 1)) == 0:
                flag = False
                result = "OK"
            elif int(resp_data.get("errcode", 1)) == 43004:  # 用户已取消关注，无需重复发送
                flag = False
                result = 43004
                logger.info("errcode=%s, counter=%s" % (result, counter))
            else:
                result = resp_data.get("errcode", 1)
                logger.info("errcode=%s, counter=%s" % (result, counter))

            counter += 1

        return result


if __name__ == "__main__":
    pass
